package com.exercise.baseskill.design.observer;

import java.util.ArrayList;

/**
 * @Author 周春桂
 * @Date 2021/4/1 15:06
 * @Desciption 被观察者角色
 **/
public abstract class Subject {
    //观察者列表
    private ArrayList<ObserverRole> observerRoles;

    public Subject() {
        observerRoles = new ArrayList<ObserverRole>();
    }

    public void attach(ObserverRole role){
        observerRoles.add(role);
    }

    public void detach(ObserverRole role){
        observerRoles.remove(role);
    }

    public void notifyObserver(int state){
        for (ObserverRole observerRole : observerRoles) {
            observerRole.notify(state)  ;
        }
    }

    public abstract int getState();

    public abstract void setState(int state);
}

/**
 * 具体被观察者
 */
class ConcreteSubject extends Subject{

    private int subjectState;

    @Override
    public int getState() {
        return subjectState;
    }

    @Override
    public void setState(int state) {
        subjectState = state;
        notifyObserver(state);
    }
}
